import 'dart:io';

import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:provider/provider.dart';

import '../model/ImageItem.dart';
import '../model/ImagePreviewViewModel.dart';
import '../model/_data.dart';

class ImageScrollWidget extends StatefulWidget {
  final ImageData imageData;

  // const ImagePreview(
  //     {super.key, required this.imageUrls, required this.currentPage});
  ImageScrollWidget({super.key, required this.imageData});

  @override
  _ImageScrollWidgetState createState() => _ImageScrollWidgetState();
}

class _ImageScrollWidgetState extends State<ImageScrollWidget> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ImagePreviewViewModel>(
        builder: (context, viewModel, child) {
      return PhotoViewGallery.builder(
          itemCount: viewModel.imageData.urls.length,
          builder: (BuildContext context, int index) {
            return PhotoViewGalleryPageOptions.customChild(
              child: buildImage(context, viewModel.images[index], viewModel),
              minScale: PhotoViewComputedScale.contained,
              maxScale: PhotoViewComputedScale.covered * 2,
            );
          },
          pageController: viewModel.pageController,
          scrollPhysics: const ClampingScrollPhysics(),
          loadingBuilder: (context, progress) => Center(
                  child: Container(
                width: 20.0,
                height: 20.0,
                child: const CircularProgressIndicator(),
              )));
    });
  }

  Widget buildImage(
      BuildContext context, ImageItem image, ImagePreviewViewModel viewModel) {
    if (image.state == ImageState.error) {
      return const Center(
        child: Text('Failed to load image'),
      );
    } else if (image.state == ImageState.loaded) {
      print('ImagePreview:  buildImage已下载 ${image.localPath}');
      return Stack(
        children: [
          PhotoView(
            imageProvider: FileImage(File(image.localPath)),
            backgroundDecoration: const BoxDecoration(
              color: Colors.black,
            ),
            minScale: PhotoViewComputedScale.contained,
            maxScale: PhotoViewComputedScale.covered * 2,
            errorBuilder: (context, error, stackTrace) {
              return const Center(
                child: Text('Failed to load image'),
              );
            },
          ),
          Positioned(
            bottom: 20,
            right: 20,
            child: ElevatedButton(
              onPressed: () {
                // Handle button press
                print('Button pressed on image $image');
              },
              child: const Text('Save'),
            ),
          ),
        ],
      );
    } else {
      print('ImagePreview:  buildImage还没有下载 ${image.localPath}');
      if (image.state == ImageState.idle) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          viewModel.downloadImage(image);
        });
      }
      return buildLoading();
    }
  }

  Widget buildLoading() {
    return Container(
      color: Colors.black, // 深色背景
      child: const Center(
        child: CircularProgressIndicator(
          value: 1,
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
        ),
      ),
    );
  }

  void saveTo() {}
}
